/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.news.filter;

import com.alibaba.fastjson.JSON;
import com.ktjiaoyu.news.entity.NewsAdmin;
import com.ktjiaoyu.news.utils.R;
import com.ktjiaoyu.news.utils.SysConstants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 通过
 * @author 科泰集团教研团队
 * @version 1.0.0
 * @packageName com.ktjiaoyu.news.filter
 * @fileName TokenFilter.java
 * @createTime 2024/5/28 8:29
 * @lastModify 2024/5/28 8:29
 */
@WebFilter(urlPatterns = "/api/admin/*")
public class AdminLoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String requestURI = request.getRequestURI();
        // 非登录请求，需要验证session
        if(!requestURI.endsWith("/login")){
            HttpSession session = request.getSession();
            //  需要登录后访问的请求进行拦截验证Session用户
            NewsAdmin loginAdmin = (NewsAdmin)session.getAttribute(SysConstants.SESSION_LOGIN_ADMIN);

            if(loginAdmin == null){
                // 拦截不允许进入其他接口
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = response.getWriter();
                R fail = R.fail(401, "未登录管理员，无权访问！", null);
                out.print(JSON.toJSONString(fail));
                return;
            }
        }


        filterChain.doFilter(servletRequest, servletResponse);
    }
}
